package com.glory.dgcpcpda.callback;

import android.util.Log;

import com.google.gson.Gson;
import com.lzy.okgo.convert.StringConvert;
import com.pda.platform.ui.ui_pdaplatform.base.FreeUI_InitUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_LogUtils;

import java.io.IOException;
import java.lang.reflect.Type;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public abstract class RequestCallBack<T> implements Callback {
    private StringConvert convert = new StringConvert();
    private Type type;

    public RequestCallBack(Type type) {
        this.type = type;
    }

    public T Body;

    public T convertResponse(Response response) throws Throwable {
        String s = this.convert.convertResponse(response);
        Log.e("json", s);
        if (FreeUI_InitUtils.isLogCrash) {
            FreeApi_LogUtils.saveErrorMessages(s, "返回JSON");
        }

        T entity = (new Gson()).fromJson(s, this.type);
        response.close();
        return entity;
    }

    @Override
    public void onFailure(Call call, IOException e) {
        FreeApi_LogUtils.saveErrorMessages(e.getMessage(), "请求异常");
    }

    @Override
    public void onResponse(Call call, Response response) throws IOException {
        try {
            Body = convertResponse(response);
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
    }
}
